package cn.kgc.crowdfundingadminspringboot.controller;


import cn.kgc.crowdfundingadminspringboot.common.ResultEntity;
import cn.kgc.crowdfundingadminspringboot.pojo.Tag;
import cn.kgc.crowdfundingadminspringboot.service.TagService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/tag")
public class TagController {

    @Resource
    TagService tagService;

    @ResponseBody
    @RequestMapping("/get/whole/tree")
    public ResultEntity<Tag> getWholeTree(){
// 1.查询所有的树形节点用于组装
        List<Tag> tagList = tagService.getAll();

        Map<Integer,Tag> tagMap = new HashMap<>();
        for (Tag tag : tagList) {
            tagMap.put(tag.getId(),tag);
        }

        // 3.声明变量用于存储根节点对象
        Tag rootNode = null;

        for (Tag tag : tagList) {
            //是父节点
            if (tag.getPid()==null){
                rootNode=tag;
                continue;
            }
            //是子节点从menuMap找到父节点，并添加到父节点的子节点集合中
            tagMap.get(tag.getPid()).getChildren().add(tag);
        }
        return ResultEntity.successWithoutData(rootNode);
    }

    @RequestMapping("/to/page.html")
    public String toPage(){
        return "tag-page";
    }

    @RequestMapping("/save")
    @ResponseBody
    public ResultEntity<String> saveTag(Tag tag) {

        tagService.saveTag(tag);

        return ResultEntity.successWithoutData();
    }


    @RequestMapping("/get/{tagId}")
    @ResponseBody
    public ResultEntity<Tag> getMenuById(@PathVariable("tagId") Integer tagId) {

        Tag tag = tagService.getTagById(tagId);

        return ResultEntity.successWithoutData(tag);
    }


    @RequestMapping("/update")
    @ResponseBody
    public ResultEntity<String> update(Tag tag){
        tagService.update(tag);
        return ResultEntity.successWithoutData();
    }

    @RequestMapping("/delete")
    @ResponseBody
    public ResultEntity<String> delete(Integer id){
        tagService.delete(id);
        return ResultEntity.successWithoutData();
    }




}
